//
//  EditScoreViewController.m
//  ScorePad
//
//  Created by Andy on 22/08/2010.
//  Copyright 2010 Mister Smith's Maevellous Mechanical Software Company. All rights reserved.
//

#import "EditScoreViewController.h"

@implementation EditScoreViewController

@synthesize delegate;

@synthesize oneHand;
@synthesize playerNames;
@synthesize numberOfPlayers;

@synthesize name0;
@synthesize score0;
@synthesize name1;
@synthesize score1;
@synthesize name2;
@synthesize score2;
@synthesize name3;
@synthesize score3;
@synthesize name4;
@synthesize score4;
@synthesize name5;
@synthesize score5;
@synthesize name6;
@synthesize score6;

@synthesize activeField;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	[super viewDidLoad];
	
	[self horribleHidingMethod];
	
	name0.text = [playerNames objectAtIndex:0];
	score0.text = [NSString stringWithFormat:@"%@", [oneHand objectAtIndex:0]];
	score0.inputView = [self numericKeyboardView];
	name1.text = [playerNames objectAtIndex:1];
	score1.text = [NSString stringWithFormat:@"%@", [oneHand objectAtIndex:1]];
	score1.inputView = [self numericKeyboardView];
	name2.text = [playerNames objectAtIndex:2];
	score2.text = [NSString stringWithFormat:@"%@", [oneHand objectAtIndex:2]];
	score2.inputView = [self numericKeyboardView];
	name3.text = [playerNames objectAtIndex:3];
	score3.text = [NSString stringWithFormat:@"%@", [oneHand objectAtIndex:3]];
	score3.inputView = [self numericKeyboardView];
	name4.text = [playerNames objectAtIndex:4];
	score4.text = [NSString stringWithFormat:@"%@", [oneHand objectAtIndex:4]];
	score4.inputView = [self numericKeyboardView];
	name5.text = [playerNames objectAtIndex:5];
	score5.text = [NSString stringWithFormat:@"%@", [oneHand objectAtIndex:5]];
	score5.inputView = [self numericKeyboardView];
	name6.text = [playerNames objectAtIndex:6];
	score6.text = [NSString stringWithFormat:@"%@", [oneHand objectAtIndex:6]];
	score6.inputView = [self numericKeyboardView];
	
	keyboardShown = NO; 
	isNumberValid = YES;
	
	self.registerForKeyboardNotifications;
	
	// Set ContentSize or UIScrollView won't, you know, scroll.	
	CGRect viewFramey = [self.view frame];
	viewFramey.size.height = [numberOfPlayers intValue] * 70;
	[(UIScrollView*)self.view setContentSize:CGSizeMake(viewFramey.size.width,viewFramey.size.height)];
	
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	
	return YES;
}


//- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
	[super viewWillAppear:NO];
	
	[self.view setNeedsDisplay];
	
	if (keyboardShown)
		[self.activeField.inputView setNeedsLayout];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewWillDisappear:(BOOL)animated {
	
	NSNumberFormatter *formatterer = [[NSNumberFormatter alloc] init];
	[formatterer setNumberStyle:NSNumberFormatterNoStyle];
		
	if ([activeField.text length] == 0)
		activeField.text = @"0";
	else {
		NSNumber *testNumber = [formatterer numberFromString:activeField.text];

		if ( (![testNumber isKindOfClass:[NSNumber class]]) ||
			([testNumber intValue] > 99999) )
			activeField.text = @"0";
	}
	
	NSArray *editedScores = [[NSArray alloc]initWithObjects:
							 [formatterer numberFromString:score0.text],
							 [formatterer numberFromString:score1.text],
							 [formatterer numberFromString:score2.text],
							 [formatterer numberFromString:score3.text],
							 [formatterer numberFromString:score4.text],
							 [formatterer numberFromString:score5.text],
							 [formatterer numberFromString:score6.text],
							 nil];	
	[formatterer release];
	
	if(delegate && [delegate respondsToSelector:@selector(scoresDataReturned:)]) 
		[delegate scoresDataReturned:editedScores]; 
	
	[editedScores release];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)horribleHidingMethod {
	score1.hidden = YES;
	name1.hidden = YES;
	score2.hidden = YES;
	name2.hidden = YES;
	score3.hidden = YES;
	name3.hidden = YES;
	score4.hidden = YES;
	name4.hidden = YES;
	score5.hidden = YES;
	name5.hidden = YES;
	score6.hidden = YES;
	name6.hidden = YES;
	
	int players = [numberOfPlayers intValue];
	
	if (players > 1) {
		score1.hidden = NO;
		name1.hidden = NO;
		if (players > 2) {
			score2.hidden = NO;
			name2.hidden = NO;
			if (players > 3) {
				score3.hidden = NO;
				name3.hidden = NO;
				if (players > 4) {
					score4.hidden = NO;
					name4.hidden = NO;
					if (players > 5) {
						score5.hidden = NO;
						name5.hidden = NO;
						if (players > 6) {
							score6.hidden = NO;
							name6.hidden = NO;
						}
					}
				}
			}
		}
	}
}


#pragma mark -
#pragma mark Keyboard Stuff

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasShown:)
												 name:UIKeyboardDidShowNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
	if (keyboardShown)
		return;
		
	NSDictionary* info = [aNotification userInfo];
	
	// Get the size of the keyboard.
	NSValue* aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
	CGSize keyboardSize = [aValue CGRectValue].size;
	
	NSLog(@"keyboardSize.height %f",keyboardSize.height); /* PENFOLD! */
	
	// Resize the scroll view (which is the root view of the window)
	CGRect viewFrame = [self.view frame];

	viewFrame.size.height -= keyboardSize.height;
	self.view.frame = viewFrame;

	[self scrollActiveTextFieldIntoView:activeField];
	
	keyboardShown = YES;	
}

- (void)scrollActiveTextFieldIntoView:(UITextField *)textField
{
	CGRect textFieldRect = [textField frame];
	[(UIScrollView*)self.view scrollRectToVisible:textFieldRect animated:YES];
	
}


#pragma mark -
#pragma mark Deal with Text Fields


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
	activeField = textField;
	
	if ([activeField.text isEqualToString:@"0"]) 
		activeField.text = @"";
	
	[self scrollActiveTextFieldIntoView:activeField];
	
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
	
	isNumberValid = NO;
	activeField.textColor = [UIColor redColor];
	
	if ([textField.text length] == 0)
		textField.text = @"0";
	
	NSNumberFormatter *formatterer = [[NSNumberFormatter alloc] init];
	[formatterer setNumberStyle:NSNumberFormatterNoStyle];
	
	NSNumber *testNumber = [formatterer numberFromString:textField.text];
	
	if ([testNumber isKindOfClass:[NSNumber class]]) {
		if ([testNumber intValue] < 99999) {
			isNumberValid = YES;
			activeField.textColor = [UIColor blackColor];
		}
	}
	
	[formatterer release];
	
	return isNumberValid;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	
	NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
	
	// Empty field
	if ([resultingString length] == 0) {
		return true;
	}
	
	NSInteger holder;
	
	NSScanner *scan = [NSScanner scannerWithString: resultingString];
	
	return [scan scanInteger: &holder] && [scan isAtEnd];
}

- (UIView *)numericKeyboardView {
	
	NSArray *keyLabels = [[NSArray alloc] initWithObjects:@"7",
						  @"8",
						  @"9",
						  @"4",
						  @"5",
						  @"6",
						  @"1",
						  @"2",
						  @"3",
						  @"-",
						  @"0",
						  @"⌫",
						  nil];
	
	int iColumn;
	int iRow;
	int keyCount = 0;
	
	CGFloat xx = self.view.frame.size.width;
	CGFloat yy = self.view.frame.size.height;

	UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

	if ((orientation == UIDeviceOrientationLandscapeLeft) ||
		(orientation == UIDeviceOrientationLandscapeRight)) {
		
		 xx = self.view.frame.size.height;
		 yy = self.view.frame.size.width;
	}
		
	UIView *theView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, xx, yy/2.5)] autorelease];
		
	theView.backgroundColor = [UIColor whiteColor];
	
	CGFloat magicWidth = theView.frame.size.width / 3 + 1;
	CGFloat magicHeight = theView.frame.size.height / 4 + 1;
	
	for (iRow = 0; iRow <4; iRow++) {
		
		for (iColumn = 0; iColumn < 3; iColumn++) {
			
			UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
			
			aButton.frame = CGRectMake(magicWidth * iColumn, 
									   magicHeight * iRow,
									   magicWidth-1,
									   magicHeight-1);
			
			[aButton setTitle:[NSString stringWithFormat:@"%@", [keyLabels objectAtIndex:keyCount]] forState:UIControlStateNormal];
			
			if ([keyLabels objectAtIndex:keyCount] == @"⌫") {
				
				[aButton addTarget:self
							action:@selector(deleteKeyPressed:)
				  forControlEvents:UIControlEventTouchDown];
			}
			else {
				
				if ([keyLabels objectAtIndex:keyCount] == @"-") {
					
					[aButton addTarget:self
								action:@selector(minusKeyPressed:)
					  forControlEvents:UIControlEventTouchDown];
				}
				else {
					[aButton addTarget:self
								action:@selector(keyPressed:)
					  forControlEvents:UIControlEventTouchDown];
					
				}
				
			}
			
			aButton.backgroundColor = [UIColor darkGrayColor];
			aButton.titleLabel.font = [UIFont boldSystemFontOfSize:28];
			[aButton setBackgroundImage:[UIImage imageNamed:@"Normal.png"] forState:UIControlStateNormal];
			[aButton setBackgroundImage:[UIImage imageNamed:@"Selected.png"] forState:UIControlStateSelected];

			keyCount++;
									
			[theView addSubview:aButton];
			
		}
	}
	
	[keyLabels release];
	
	return theView;
}

- (void) keyPressed:(id) sentButton {

	UIButton *theButton = (UIButton *)sentButton;
		
	activeField.text = [activeField.text stringByAppendingString:theButton.titleLabel.text];

}

- (void) minusKeyPressed:(id) sentButton {
	
	if ( [activeField.text length] == 0 )
		activeField.text = @"-";
	
}

- (void) deleteKeyPressed:(id) sentButton {
		
	if ( [activeField.text length] > 0 )
		activeField.text = [activeField.text substringToIndex:[activeField.text length] - 1];
	
}


- (void)dealloc {
		
	[oneHand release];
	[playerNames release];
	[numberOfPlayers release];
	
	[name0 removeFromSuperview];
	[score0 removeFromSuperview];
	[name1 removeFromSuperview];
	[score1 removeFromSuperview];
	[name2 removeFromSuperview];
	[score2 removeFromSuperview];
	[name3 removeFromSuperview];
	[score3 removeFromSuperview];
	[name4 removeFromSuperview];
	[score4 removeFromSuperview];
	[name5 removeFromSuperview];
	[score5 removeFromSuperview];
	[name6 removeFromSuperview];
	[score6 removeFromSuperview];
	
	[activeField release];
		
	[super dealloc];
	
}

@end
